package com.ct.service.entity;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.ct.entity.po.Reimbursement;
import com.ct.entity.query.ReimbursementQuery;
import com.ct.entity.vo.ReimbursementReportVO;
import com.ct.mappers.ReportMapper;

/**
 * @Description:
 * @Author: cby
 * @Date: 2025/5/23 17:51
 */
public class BarDataStrategy implements ReportDataStrategy<List<ReimbursementReportVO>> {
    private ReportMapper<Reimbursement, ReimbursementQuery> reportReimbursementMapper;

    public BarDataStrategy(ReportMapper<Reimbursement, ReimbursementQuery> reportReimbursementMapper) {
        this.reportReimbursementMapper = reportReimbursementMapper;
    }

    @Override
    public List<ReimbursementReportVO> getData(Date startDate, Date endDate) {
        List<ReimbursementReportVO> dataList = new ArrayList<>();
        List<Reimbursement> sourseList = reportReimbursementMapper.selectSumCountByDate(startDate, endDate);
        initDataList(startDate, endDate, dataList);
        for (Reimbursement r : sourseList) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(r.getApplyDate());
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH);

            for (ReimbursementReportVO report : dataList) {
                Calendar reportCalendar = Calendar.getInstance();
                reportCalendar.setTime(report.getDate());
                int reportYear = reportCalendar.get(Calendar.YEAR);
                int reportMonth = reportCalendar.get(Calendar.MONTH);

                if (reportYear == year && reportMonth == month) {
                    BigDecimal currentCount = report.getCount() != null ? report.getCount() : BigDecimal.ZERO;
                    BigDecimal totalCost = r.getFoodCost().add(r.getTransportCost()).add(r.getHotelCost());
                    report.setCount(currentCount.add(totalCost));
                    break;
                }
            }
        }
        return dataList;
    }

    private void initDataList(Date start, Date end, List<ReimbursementReportVO> dataList) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(start);

        while (calendar.getTime().before(end) || calendar.getTime().equals(end)) {
            ReimbursementReportVO report = new ReimbursementReportVO();
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            report.setDate(calendar.getTime());
            report.setCount(BigDecimal.ZERO);
            dataList.add(report);
            calendar.add(Calendar.MONTH, 1);
        }
    }
}
